<template>
    <el-drawer
      v-model="modelDrawer"
      :title="isEdit ? '编辑用户' : '新增用户'"
      direction="rtl"
      size="40%"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        label-position="left"
      >


      <!-- 角色选择 -->
      <el-form-item label="角色" prop="roleId">
        <el-select v-model="formData.roleId" placeholder="请选择角色">
          <el-option
            v-for="role in roleOptions"
            :key="role.value"
            :label="role.label"
            :value="role.value"
          />
        </el-select>
      </el-form-item>

        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="formData.realName" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="formData.password" type="password" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" type="primary" @click="submitForm">提交</el-button>
          <el-button @click="closeForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </template>
  
  <script setup lang="ts">
  import { ref, watch,computed } from 'vue'
  import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
  import { userMangerApi } from '@/api/user'
  import type { User } from '@/types/user'
  
  const props = defineProps({
    isEdit: Boolean,
    rowData: {
      type: Object as () => User | null,
      default: null
    }
  })

  // 抽屉显示状态
  const modelDrawer = defineModel()

  // 事件
  const emit = defineEmits(['update:visible', 'refresh'])
  
  // 表单引用
  const formRef = ref<FormInstance>()
  // 表单数据
  const formData = ref<User>({
    userName: '',
    realName: '',
    password: '',
    email: '',
    status: 1,
    roleId:null,
  })

  // 角色选项
const roleOptions = [
  { value: 1, label: '学生' },
  { value: 2, label: '教师' },
  { value: 3, label: '管理员' }
]
  
  // 验证规则
  const rules = ref<FormRules>({
    userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    roleId: [{ required: true, message: '请选择角色', trigger: 'change' }]
  })
  
  // 监听visible变化
  watch(
    () => modelDrawer.value,
    (val) => {
        console.log('watch-visible变化', val)
      if (val) {
        // 编辑时填充数据
        if (props.isEdit && props.rowData) {
          formData.value = { ...props.rowData,
            password: '' // 密码置空，不显示原有密码
        }
        } else {
          // 新增时重置表单
          formData.value = {
            userName: '',
            realName: '',
            password: '',
            email: '',
            roleId: null,
            status: 1
          }
        }
      }
    }
  )


  // 提交表单
  const loading = ref(false); // 防止重复提交
  
  const submitForm = async () => {
    try {
      await formRef.value?.validate();
  
      loading.value = true;
  
      const api = props.isEdit ? userMangerApi.update : userMangerApi.add;
      const { code, msg } = await api(formData.value);
      if (code === 1) {
        ElMessage.success(msg);
        modelDrawer.value = false;
        emit('refresh');
      } else {
        ElMessage.error(msg);
      }
    } catch (error) {
      // 区分验证失败和其他错误
      if (error instanceof Error && error.message.includes('validate')) {
        ElMessage.error('请检查表单填写是否正确');
      } else {
        console.error(error);
        ElMessage.error('提交过程中发生错误');
      }
    } finally {
      loading.value = false;
    }
  };

  // 关闭表单
  const closeForm = () => {
    console.log('关闭表单')
    modelDrawer.value = false
  }

  </script>